<template>
  <div class="theme-content-item" style="position: relative;">
    <div class="padding-20px form-style">
      <div class="left-title">{{ title }}</div>
      <el-form ref="bankFormRef" :model="form" :rules="rules" label-width="120px"
               style="margin-top: 40px">
        <el-row style="display: flex;justify-content:start">
          <!--          <el-col :span="10">-->
          <!--            <el-form-item label="名称" prop="name">-->
          <!--              <el-input v-model="form.name" placeholder="请输入名称"></el-input>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="10">
            <el-form-item label="课程类型" prop="courseType">
              <el-cascader ref="courseTypeRef" v-model="form.courseType" :options="data.courseList"
                           :props="{label:'name',value:'id',children:'children',emitPath:false}" placeholder="请选择课程类型"
                           @change="changeCourseHandle"/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="类型" prop="type">
              <el-select v-model="form.type" clearable placeholder="请选择类型">
                <el-option v-for="item in data.bankTypeList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="关联建培圈内容" prop="assocOutBankList">
              <el-select v-model="form.assocOutBankList" clearable collapse-tags
                         collapse-tags-tooltip
                         multiple placeholder="请选择关联内容" @change="changeAssoBankHandle">
                <el-option v-for="item in data.assoBankList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="10">-->
          <!--            <el-form-item label="排序" prop="orderNum">-->
          <!--              <el-input type="number" v-model="form.orderNum" placeholder="请输入排序号"></el-input>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="10">
            <el-form-item label="状态" prop="publishedFlag">
              <el-radio v-model="form.publishedFlag" :label="1">上架</el-radio>
              <el-radio v-model="form.publishedFlag" :label="0">下架</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="说明">
              <el-input v-model="form.remark" placeholder="请输入说明" type="textarea"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="flex-jc-s-b" style=" position: fixed; bottom: 5%; left: 45%">
        <el-button size="small" @click="goBack()">
          <svg-icon class="el-input__icon input-icon" icon-class="back"/>
          <span style="margin-left: 5px;">关 闭</span>
        </el-button>
        <el-button size="small" style="margin-left: 20px;" type="primary" @click="save">
          <svg-icon class="el-input__icon input-icon" icon-class="save"/>
          <span style="margin-left: 5px;">保 存</span>
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {useRoute, useRouter} from 'vue-router'
import {addMoreBank, getBankDetail} from '@/api/resource/bank'
import {listDictItemByCode} from '@/api/config/dic'
import {listAssoBank} from '../../../../api/resource/bank'

const {proxy} = getCurrentInstance();
const route = useRoute()
const router = useRouter()
const routeQuery = reactive(route.query)
const title = ref('');
const isAdd = ref(false);
const data = reactive({
  courseList: [],
  bankTypeList: [],
  teacherList: [],
  docList: [],
  assoBankList: []
})
const form = reactive({
  courseType: '',
  type: '',
  year: '',
  publishedFlag: 1,
  remark: '',
  courseTypeName: '',
  assocOutBankList: []
})

const rules = ({
  name: [{required: true, message: '请输入名称', trigger: 'blur'}],
  courseType: [{required: true, message: '请选择课程类型', trigger: 'blur'}],
  type: [{required: true, message: '请选择类型', trigger: 'blur'}],
  assocOutBankList: [{required: true, message: '请选择题库', trigger: 'blur'}],
  publishedFlag: [{required: true, message: '请选择状态', trigger: 'blur'}],
  orderNum: [{required: true, message: '请输入排序号', trigger: 'blur'}],
})

// 详情
const initDetail = (row) => {
  getBankDetail(row.id || route.query.id).then((res) => {
    let resData = res.data
    Object.keys(form).forEach((key) => {
      form[`${key}`] = resData[`${key}`]
    })
    form.assocOutBankList = []
    listAssoBank({levelNum: 2, courseName: form.courseTypeName, typeCode: 'practise'}).then(res => {
      res.rows.forEach(item => {
        form.assocOutBankList.push(item.id)
      })
      data.assoBankList = res.rows
    })
  })
}
const initData = () => {
  listDictItemByCode({typeCode: 'courseTypeCode'}).then(res => {
    data.courseList = res.rows
  })
  listDictItemByCode({typeCode: 'bankTypeCode'}).then(res => {
    data.bankTypeList = res.rows
  })
}

function changeCourseHandle() {
  data.assoBankList = []
  let courseTypeRef = proxy.$refs["courseTypeRef"]
  let pathLabels = courseTypeRef.getCheckedNodes()[0].pathLabels
  form.courseTypeName = pathLabels[0] + '-' + pathLabels[1]
  form.assocOutBankList = []
  listAssoBank({levelNum: 2, courseName: form.courseTypeName, typeCode: 'practise'}).then(res => {
    res.rows.forEach(item => {
      form.assocOutBankList.push(item.id)
    })
    data.assoBankList = res.rows
  })
}

function changeAssoBankHandle(val) {
  // let selectedAssoBankItem = data.assoBankList.find(item => item.id == val)
  // form.assoBankName = selectedAssoBankItem.name
  // form.questionCount = selectedAssoBankItem.questionAmount
  // form.assoCourseId = selectedAssoBankItem.courseId
}

const save = () => {
  proxy.$refs["bankFormRef"].validate(valid => {
    let arr = []
    data.assoBankList.forEach(item => {
      let index = form.assocOutBankList.findIndex(ids => ids == item.id)
      if (index >= 0) {
        arr.push({
          "assoBankId": item.id,
          "assoBankName": item.name,
          "questionCount": item.questionAmount,
          "assoCourseId": item.courseId
        })
      }
    })
    form.assocOutBankList = arr
    addMoreBank(form).then(res => {
      if (res.code === 200) {
        clearForm()
        ElMessage.success('添加成功');
      }
    })
  })
}

function goBack() {
  proxy.$tab.closeOpenPage();
  router.go(-1)
}

function clearForm() {
  Object.keys(form).forEach((key) => {
    form[key] = ''
  })
  form.publishedFlag = 1
}

onMounted(() => {
  let titleMap = {
    add: '新增',
    edit: '修改',
  }
  routeQuery.type ? title.value = titleMap[routeQuery.type] : ''
  routeQuery.type == 'edit' ? initDetail(route.query) : ''
  isAdd.value = routeQuery.type == 'add'
  initData()
})
</script>
